import Decorator from '../core/Decorator';
import { FAILURE, ERROR } from '../constants';
import Tick from '../core/Tick';
import BaseNode from '../core/BaseNode';

export default class RepeatUntilSuccess extends Decorator {
  maxLoop: number

  constructor(child: BaseNode, maxLoop = -1) {
    super(`RepeatUntilSuccess[${maxLoop}]`, child);
    this.addProperties('maxLoop', maxLoop)
    this.maxLoop = maxLoop;
  }

  onOpen(tick: Tick, ...args: any[]) {
    tick.blackboard.set('i', 0, tick.tree.id, this.id);
  }

  onTick(tick: Tick, ...args: any[]) {
    let i = tick.blackboard.get('i', tick.tree.id, this.id);
    let status = ERROR;

    while (this.maxLoop < 0 || i < this.maxLoop) {
      status = this.child.execute(tick, ...args);

      if (status == FAILURE) {
        i++;
      } else {
        break;
      }
    }

    i = tick.blackboard.set('i', i, tick.tree.id, this.id);
    return status;
  }
};
